<?php
/**
 * Core_Personal_SignupForm
 * 
 * @author naspeh
 * @version $Id: SignupForm.php 671 2008-06-30 12:06:16Z naspeh $
 */
class Core_Personal_SignupForm extends Core_Form 
{
    /**
     * Инициализация
     *
     * @return Core_Personal_SignupForm
     */
    public function init()
    {
        $this->addElement('text', 'name', array(
            'required' => true,
            'label'    => 'Логин:',
            'attribs'  => array(
                'class' => 'text span-4',
                'size'  => 16
            ),     
            'validators' => array(
                new Zend_Validate_Alnum(),
                new Zend_Validate_StringLength(3,16),
                new Core_Validate_UsernameExist()
            )
        ));
        $this->addElement('text', 'email', array(
            'required' => true,
            'label'    => 'Email:',
            'attribs'  => array(
                'class' => 'text span-4',
            ),     
            'validators' => array(
                new Zend_Validate_EmailAddress(),
                new Core_Validate_EmailExist()
            )
        ));
        $this->addElement('password', 'password', array(
            'required' => true,
            'label'    => 'Пароль:',
            'attribs'  => array(
                'class' => 'text span-4',
            )
        ));
        $this->addElement('password', 'password_confirm', array(
            'required' => true,
            'label'    => 'Подтверждение пароля:',
            'attribs'  => array(
                'class' => 'text span-4',
            )
        ));
        $this->addElement('text', 'fullname', array(
            'required' => true,
            'label'    => 'Полное имя:',
            'attribs'  => array(
                'class' => 'text span-4',
                'size'  => 32
            ),     
            'validators' => array(
                new Zend_Validate_StringLength(3,32),
                new Zend_Validate_Alnum(true)
            )
        ));
        $this->addElement('button', 'submit', array(
            'type'     => 'submit',
            'label'    => 'Отправить',
            'attribs'  => array(
                'class' => 'positive',
                'icon'  => 'tick'
            )
        ));
        return $this;
    }
    /**
     * Вторичная валидация
     *
     * @return Core_Personal_SignupForm
     */
    protected function _setPostValid()
    {
        $this->getElement('password_confirm')->addValidator(new Core_Validate_PasswordConfirm());
        return $this;
    }
    /**
     * Запускает форму на выполнение
     *
     * @return Core_Personal_SignupForm
     */
    public function process()
    {
        $tableRoles = new Core_Table_Roles();
        $values = $this->getValues(true);
        $data = array(
            'name'     => $values['name'],
            'password' => md5($values['password']),
            'email'    => $values['email'],
            'fullname' => $values['fullname'],
        );
        if (Core_Auth::getEnableActive()) {
            $codeConfirm = Core_Auth::getHash($data['name']);
            $data['is_login'] = false;
            $data['code_confirm'] = $codeConfirm;
        } else {
            $data['is_login'] = true;
        }
        $db = Core_Db::getInstance();
        $db->beginTransaction();
        $isError = false;
        if (false === ($resultId = $tableRoles->insert($data))) {
            $isError = true;
        } else {
            $tableRolesTies = new Core_Table_RoleTies();
            $parent = $tableRoles->fetchRow(array('name = ?' => Core_Auth::REGISTER_ROLE));
            if (false === $tableRolesTies->insert(array('role_id' => $resultId, 'parent' => $parent->id))) {
                $isError = true;
            }
        }
        if ($isError) {
            $db->rollBack();
            throw new Core_Exception('databaseError# Ошибка вставки в таблицу пользователя.');
        } else {
            $db->commit();
            Core_Message::add('Регистрация прошла успешно. На Ваш email выслана ссылка активации.');
            if (isset($codeConfirm)) {
                Core_Informant::run($data['email'], 'signup-enabled-active', array(
                    'login' => $data['name'],
                    'password' => $values['password'],
                    'code_confirm' => $codeConfirm
                ));
            } else {
                Core_Informant::run($data['email'], 'signup-easy', array(
                    'login' => $data['name'],
                    'password' => $values['password'],
                ));
            }
            Core_Auth::authenticate($data['name'], $values['password']);
        }
        return $this;
    }
}